<template>
  <!-- 员工管理 -->
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="员工姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入员工姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="员工编码" prop="userNo">
        <el-input v-model="queryParams.userNo" placeholder="请输入员工编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="账号类型" prop="accountType">
        <el-select v-model="queryParams.accountType" placeholder="请选择账号类型" clearable size="small"
                   @change="getBusinessLists1">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.app_account_type)" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="商户名称" prop="tenantId">
        <el-select v-model="queryParams.tenantId" @change="chooseTenant" filterable clearable placeholder="请输入商户名称"
                   @keyup.enter.native="handleQuery">
          <el-option v-for="tenant in tenants1" :key="tenant.id" :label="tenant.name" :value="parseInt(tenant.id)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="分公司名称" prop="subTenantId">
        <el-select v-model="queryParams.subTenantId" @change="chooseSubTenant" filterable clearable placeholder="请输入分公司名称"
                   @keyup.enter.native="handleQuery">
          <el-option v-for="subTenant in subTenants" :key="subTenant.id" :label="subTenant.name"
                     :value="parseInt(subTenant.id)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="门店名称" prop="shopId">
        <el-select v-model="queryParams.shopId" filterable clearable placeholder="请输入门店名称" @keyup.enter.native="handleQuery">
          <el-option v-for="shop in shops" :key="shop.id" :label="shop.name" :value="parseInt(shop.id)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="queryParams.roleId" filterable clearable placeholder="请选择角色">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="parseInt(item.id)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="queryParams.enabled" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.pc_enable_disable_status)" :key="dict.value"
                     :label="dict.label" :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
                   v-hasPermi="['pekingfish:tenantuser:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="small" @click="handleImport"
                   v-hasPermi="['pekingfish:tenantuser:import']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="small" @click="handleExport"
                   :loading="exportLoading" v-hasPermi="['pekingfish:tenantuser:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="操作" align="center" fixed="left" class-name="small-padding fixed-width" width="100">
        <template v-slot="scope">
          <el-button size="small" @click="handleService(scope.row, 'edit')" type="text"
                     v-hasPermi="['pekingfish:tenantuser:getServicePhone']"
          >联系客户
          </el-button>
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['pekingfish:tenantuser:update']">修改
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="员工姓名" align="center" prop="userName" fixed="left"/>
      <el-table-column label="员工编码" align="center" prop="userNo"/>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="信用等级" align="center" prop="grade"/>
      <el-table-column label="角色" align="center" prop="roleName"/>
      <el-table-column label="账号类型" align="center" prop="accountType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.app_account_type" :value="scope.row.accountType"/>
        </template>
      </el-table-column>
      <el-table-column label="商户名称" align="center" prop="tenantName"/>
      <el-table-column label="分公司名称" align="center" prop="subTenantName"/>
      <el-table-column label="门店名称" align="center" prop="shopName"/>
      <el-table-column label="状态" align="center" prop="enabled" width="100">
        <template v-slot="scope">
          <el-switch @change="changeSwitch(scope.row)" v-model="scope.row.enabled" :active-value="0"
                     :inactive-value="1"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="700px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="账号类型" prop="accountType">
          <el-select :disabled="form.id?true:false" style="width: 100%;" v-model="form.accountType"
                     placeholder="请选择账号类型" clearable @change="changeAccount">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.app_account_type)" :key="dict.value"
                       :label="dict.label" :value="parseInt(dict.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入员工姓名"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11"/>
        </el-form-item>

        <!-- <el-form-item label="员工类型" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.app_user_type)" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="商户名称" prop="tenantId">
          <el-select :disabled="form.id?true:false" style="width: 100%;" v-model="form.tenantId" @change="chooseTenant"
                     clearable placeholder="请选择商户名称">
            <el-option v-for="tenant in tenants" :key="tenant.id" :label="tenant.name" :value="parseInt(tenant.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.accountType == 1" label="分公司名称" prop="subTenantId">
          <el-select :disabled="form.id?true:false" style="width: 100%;" v-model="form.subTenantId"
                     @change="chooseSubTenant" clearable placeholder="请选择分公司名称">
            <el-option v-for="subTenant in subTenants" :key="subTenant.id" :label="subTenant.name"
                       :value="parseInt(subTenant.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.accountType == 1" label="门店名称" prop="shopId">
          <el-select :disabled="form.id?true:false" style="width: 100%;" v-model="form.shopId" clearable
                     placeholder="请选择门店名称">
            <el-option v-for="shop in shops" :key="shop.id" :label="shop.name" :value="parseInt(shop.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.accountType == 1" label="角色" prop="roleId">
          <el-select style="width: 100%;" v-model="form.roleId" clearable placeholder="请选择角色">
            <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="parseInt(item.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-radio-group v-model="form.enabled">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.pc_enable_disable_status)" :key="dict.value"
                      :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <importUploadFile :visible.sync="visibleImportFile" :fetchFun="fetchFunImport" :importTemplate="importTemplate"
                      @done="getList" templateTitle="员工模板"/>
  </div>
</template>

<script>
import {businessListsAll, subtenantListsAll} from '@/api/merchantManagement/business';
import {
  addTenantUser,
  updateTenantUser,
  tenantUserList,
  exportTenantUser,
  importTenantUser,
  importTenantUserTemplate,
  getService
} from '@/api/merchantManagement/employee'
import {getCompanyByType} from '@/api/merchantManagement/branchCompany'
import {getBranchCompanyByTenantId} from '@/api/merchantManagement/branchCompany'
import {getStoreBySuTenantId} from '@/api/merchantManagement/store'
import { listSimpleRoles, listSimpleRolesTel } from '@/api/system/role'
import ImageUpload from '@/components/ImageUpload'
import ImagePreview from '@/components/ImagePreview'
import importUploadFile from "@/components/importUploadFile";

export default {
  name: 'AppUser',
  components: {
    ImageUpload,
    ImagePreview,
    importUploadFile
  },
  data() {
    return {
      visibleImportFile: false,
      fetchFunImport: importTenantUser,
      importTemplate: importTenantUserTemplate,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工管理列表
      list: [],
      // 商户名称
      tenants: [],
      tenants1: [],
      // 分公司名称
      subTenants: [],
      //门店名称
      shops: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        userName: null,
        phone: null,
        accountType: null,
        tenantId: null,
        subTenantId: null,
        shopId: null,
        roleId: null,
        enabled: null,
        userType: null

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [{required: true, message: '员工姓名不能为空', trigger: 'blur'}],
        phone: [{required: true, message: '手机号码不能为空', trigger: 'blur'}],
        accountType: [{required: true, message: '账户类型不能为空', trigger: 'change'}],
        tenantId: [{required: true, message: '商户名称不能为空', trigger: 'change'}]
      },
      // 角色列表
      roleOptions: []
    }
  },
  created() {
    this.getRolesLists();
    this.getList();
    this.getBusinessLists1();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      tenantUserList(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    changeSwitch(data) {
      updateTenantUser(data).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.getList()
      })
    },
    // 商户列表
    getBusinessLists(type) {
      businessListsAll({type: type}).then(response => {
        this.tenants = response.data
      })
    },
    getBusinessLists1() {
      this.queryParams.tenantId = null;
      this.queryParams.subTenantId = null;
      this.queryParams.shopId = null;
      this.subTenants = [];
      this.shops = [];
      businessListsAll({type: this.queryParams.accountType}).then(response => {
        this.tenants1 = response.data
      })
    },
    //通过商户查询 分公司
    chooseTenant(tenantId) {
      this.form.subTenantId = null;
      this.form.shopId = null;
      this.getsubtenantListsAll(tenantId)
    },
    getsubtenantListsAll(tenantId) {
      subtenantListsAll({tenantId: tenantId}).then(response => {
        this.subTenants = response.data;
      })
    },
    //通过分公司查询 门店
    chooseSubTenant(subTenantId) {
      this.form.shopId = null;
      this.getStoreBySuTenanList(subTenantId)
    },
    getStoreBySuTenanList(subTenantId) {
      getStoreBySuTenantId(subTenantId).then(response => {
        this.shops = response.data;
      })
    },
    //
    // 获得角色列表
    getRolesLists() {
      this.roleOptions = [];
      listSimpleRolesTel().then(response => {
        this.roleOptions.push(...response.data);
      });
    },
    // 切换账号类型
    changeAccount() {
      this.form.tenantId = null;
      this.form.subTenantId = null;
      this.form.shopId = null;
      this.form.roleId = null;
      this.getBusinessLists(this.form.accountType);
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        pageNo: 1,
        pageSize: 10,
        id: undefined,
        userName: undefined,
        phone: undefined,
        accountType: undefined,
        tenantId: undefined,
        subTenantId: undefined,
        shopId: undefined,
        roleId: undefined,
        enabled: 0,
        userType: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加员工管理'
    },
    /** 联系客户操作 */
    handleService(row) {
      const phone = row.phone
      this.$modal.confirm('是否确认联系"' + phone + '"的客户?').then(function () {
        return getService(row.phone)
      }).then(() => {
        window.location.href = 'https://xiaokefu.com.cn/zhimaOpen/OpenThirdContact/index?params[0]=' + encodeURI('{"h5_openid":"' + phone + '"}')
      }).catch(() => {
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      this.title = '修改员工管理';
      this.getBusinessLists(row.accountType);
      if (row.tenantId) {
        this.getsubtenantListsAll(row.tenantId)
      }
      if (row.subTenantId) {
        this.getStoreBySuTenanList(row.subTenantId)
      }
      this.form = JSON.parse(JSON.stringify(row));
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        // 修改的提交
        this.loading = true;
        if (this.form.id) {
          updateTenantUser(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
            this.loading = false
          }).catch(f => {
            this.loading = false
          })

        } else {
          // 添加的提交
          addTenantUser(this.form).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.getList()
            this.loading = false
          }).catch(f => {
            this.loading = false
          })
        }

      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除员工管理编号为"' + id + '"的数据项?').then(function () {
        return deleteAppUser(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams}
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有员工管理数据项?').then(() => {
        this.exportLoading = true
        return exportTenantUser(params)
      }).then(response => {
        this.$download.excel(response, '员工管理.xls')
        this.exportLoading = false
      }).catch(() => {
      })
    },
    handleImport() {
      this.visibleImportFile = true
    }
  }
}
</script>
